package com.yanxu.client;

import java.io.*;
import java.net.Socket;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-05-29-2025
 * @Description: 这里用一句话描述这个类的作用
 */
public class ChatClient {

    private Socket socket;
    private BufferedReader reader;
    private BufferedWriter writer;

    /* 发送消息到服务器 */
    public void sendMessage(String message) throws IOException {
        if (!socket.isOutputShutdown()) {
            writer.write(message);
            writer.flush();
        }
    }

    /* 从服务器接收消息 */
    public String receiveMessage() throws IOException {
        String msg = null;
        if (!socket.isInputShutdown()) {
            msg = reader.readLine();
        }
        return msg;
    }

    /* 释放资源 */
    public void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void start() {
        try {
            // 创建 socket
            socket = new Socket("127.0.0.1", 7777);
            // 创建连接需要的 reader、writer
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            // 处理用户的输入
            new Thread(new UserInputHandler(this)).start();

            // 读取服务端发送过来消息
            String msg;
            while ((msg = receiveMessage()) != null) {
                System.out.println(msg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(socket);
        }
    }

    public static void main(String[] args) {
        ChatClient client = new ChatClient();
        client.start();
    }
}